package com.xuxin.nantai.activity.chou;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.king.zxing.Intents;
import com.xuxin.nantai.R;
import com.xuxin.nantai.activity.MyCaptureActivity;
import com.xuxin.nantai.base.BaseActivity;
import com.xuxin.nantai.base.BaseConstant;
import com.xuxin.nantai.base.BaseTextWatcher;
import com.xuxin.nantai.bean.AllAreaBean;
import com.xuxin.nantai.bean.BaseBean;
import com.xuxin.nantai.bean.GroupBean;
import com.xuxin.nantai.bean.HangUpdateLoginBean;
import com.xuxin.nantai.bean.InspectorBean;
import com.xuxin.nantai.bean.SelectFlowingBean;
import com.xuxin.nantai.contract.AllAreaContract;
import com.xuxin.nantai.contract.SelectUpdateContract;
import com.xuxin.nantai.presenter.AllAreaPresenter;
import com.xuxin.nantai.presenter.SelectUpdatePresenter;
import com.xuxin.nantai.utils.ACache;
import com.xuxin.nantai.utils.FlowingUtils;
import com.xuxin.nantai.utils.TimeUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by xu_xin
 * Created on 2020.06.12 0012
 * 缝制抽检新增修改
 */
public class SelectUpdateActivity extends BaseActivity implements SelectUpdateContract.View, AllAreaContract.View {
    private SelectUpdateContract.Presenter presenter = new SelectUpdatePresenter(this);
    private AllAreaContract.Presenter presenter2 = new AllAreaPresenter(this);
    @BindView(R.id.title_left)
    ImageView title_left;
    @BindView(R.id.title_right)
    ImageView title_right;
    @BindView(R.id.title_name)
    TextView title_name;

    @BindView(R.id.select_update_team)
    TextView select_update_team;//组检
    @BindView(R.id.select_update_reCheck)
    CheckBox select_update_reCheck;//是否复检
    @BindView(R.id.select_update_flowing)
    EditText select_update_flowing;//流转单号
    @BindView(R.id.select_update_search)
    ImageView select_update_search;//搜索
    @BindView(R.id.select_update_scan)
    ImageView select_update_scan;//扫描
    @BindView(R.id.select_update_name)
    TextView select_update_name;//成品名称
    @BindView(R.id.select_update_pack)
    TextView select_update_pack;//本包数
    @BindView(R.id.select_update_com)
    EditText select_update_com;//部件数
    @BindView(R.id.select_update_percent)
    EditText select_update_percent;//抽检比例
    @BindView(R.id.select_update_check)
    TextView select_update_check;//抽检数
    @BindView(R.id.select_update_area)
    TextView select_update_area;//厂区
    @BindView(R.id.select_update_group)
    TextView select_update_group;//生产组别
    @BindView(R.id.select_update_inspector)
    TextView select_update_inspector;//巡检员
    @BindView(R.id.select_update_time)
    TextView select_update_time;//检验日期
    @BindView(R.id.select_update_result)
    TextView select_update_result;//判定结果
    @BindView(R.id.select_update_mark)
    EditText select_update_mark;//备注

    private String Guid;//唯一Guid
    private String ID;//唯一ID
    private String teamType;//组检单检
    private int reCheck;//是否复检
    private String flowingCode;//流转单号
    private String cInvName;//成品名
    private String cInvCode;//成品编码
    private String packNum;//本包数
    private String comNum;//部件数
    private String percent;//抽检比例
    private String checkNum;//抽检数
    private String area;//厂区
    private String groupName;//生产组别名称
    private String groupCode;//生产组别代码
    private String inspectorName;//巡检员名
    private String inspectorCode;//巡检员代码
    private String inspectorTime;//检验日期
    private String result;//判定结果
    private String mark;//备注

    private MaterialDialog materialDialog;
    private MaterialDialog commitDialog;

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_select_update);
    }

    @Override
    public void initView() {
        Bundle bundle = getIntent().getExtras();
        if (null != bundle && !StringUtils.isEmpty(bundle.getString("Guid"))) {
            //修改
            title_name.setText("缝制抽检修改");
            Guid = bundle.getString("Guid");
            ID = bundle.getString("ID");
            teamType = bundle.getString("teamType");
            reCheck = bundle.getInt("reCheck");
            flowingCode = bundle.getString("flowingCode");
            cInvName = bundle.getString("cInvName");
            cInvCode = bundle.getString("cInvCode");
            packNum = bundle.getString("packNum");
            comNum = bundle.getString("comNum");
            percent = bundle.getString("percent");
            checkNum = bundle.getString("checkNum");
            area = bundle.getString("area");
            groupName = bundle.getString("groupName");
            groupCode = bundle.getString("groupCode");
            inspectorName = bundle.getString("inspectorName");
            inspectorCode = bundle.getString("inspectorCode");
            inspectorTime = bundle.getString("inspectorTime");
            result = bundle.getString("result");
            mark = bundle.getString("mark");

            LogUtils.e("Guid = " + Guid);
            LogUtils.e("ID = " + ID);
            LogUtils.e("teamType = " + teamType);
            LogUtils.e("reCheck = " + reCheck);
            LogUtils.e("flowingCode = " + flowingCode);
            LogUtils.e("cInvName = " + cInvName);
            LogUtils.e("cInvCode = " + cInvCode);
            LogUtils.e("packNum = " + packNum);
            LogUtils.e("comNum = " + comNum);
            LogUtils.e("percent = " + percent);
            LogUtils.e("checkNum = " + checkNum);
            LogUtils.e("area = " + area);
            LogUtils.e("groupName = " + groupName);
            LogUtils.e("groupCode = " + groupCode);
            LogUtils.e("inspectorName = " + inspectorName);
            LogUtils.e("inspectorCode = " + inspectorCode);
            LogUtils.e("inspectorTime = " + inspectorTime);
            LogUtils.e("result = " + result);
            LogUtils.e("mark = " + mark);
            LogUtils.e("--------------------------");
            select_update_team.setText(teamType);
            select_update_reCheck.setChecked(1 == reCheck);
            select_update_flowing.setText(flowingCode);
            select_update_name.setText(cInvName);
            select_update_pack.setText(packNum);
            select_update_com.setText(comNum);
            select_update_percent.setText(percent);
            select_update_check.setText(checkNum);
            select_update_area.setText(area);
            select_update_group.setText(groupName);
            select_update_inspector.setText(inspectorName);
            select_update_time.setText(inspectorTime);
            select_update_result.setText(result);
            select_update_mark.setText(mark);
            LogUtils.e("缝制抽检修改_ID = " + Guid);

            //部件数,抽检比例 输入监控
            select_update_com.addTextChangedListener(new myTextWatcher());
            select_update_percent.addTextChangedListener(new myTextWatcher());
        } else {
            title_name.setText("缝制抽检新增");
            LogUtils.e("缝制抽检新增_ID = " + Guid);
        }
        //流转单输入监控
        select_update_flowing.addTextChangedListener(new BaseTextWatcher() {
            @Override
            public void onTextChanged(String message) {
                cInvName = null;
                cInvCode = null;
                packNum = null;
                comNum = null;
                percent = null;
                checkNum = null;
                select_update_name.setText("");
                select_update_pack.setText("");
                select_update_com.setText("");
                select_update_percent.setText("");
                select_update_check.setText("");
            }
        });
        //新增
        if (StringUtils.isEmpty(Guid)) {
            //默认日期今天
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
            Date date = new Date(System.currentTimeMillis());
            inspectorTime = simpleDateFormat.format(date);
            select_update_time.setText(inspectorTime);
            //给个默认的判定结果
            result = "合格";
            select_update_result.setText(result);
        }
    }

    @Override
    public void initData() {
        if (StringUtils.isEmpty(Guid)) {
            //新增
            handler.sendEmptyMessage(6);//获取默认厂
        }
        handler.sendEmptyMessage(0);//获取所有生产组别
        handler.sendEmptyMessage(1); //根据单检组检获取检验员
        handler.sendEmptyMessage(3);//获取厂区列表
    }

    @Override
    public void onComplete() {
        if (null != commitDialog) {
            commitDialog.dismiss();
        }
    }

    @Override
    @OnClick({R.id.title_left, R.id.select_update_team, R.id.select_update_inspector,
            R.id.select_update_search, R.id.select_update_group, R.id.select_update_time,
            R.id.select_update_scan, R.id.select_update_result, R.id.select_update_update,
            R.id.select_update_area})
    public void onClick(View view) {
        KeyboardUtils.hideSoftInput(this);
        switch (view.getId()) {
            case R.id.title_left:
                finish();
                break;
            case R.id.select_update_team:
                new MaterialDialog.Builder(this)
                        .items("组检", "单检")
                        .itemsCallback((dialog, view1, position, text) -> {
                            try {
                                teamType = (position == 0 ? "组检" : "单检");
                                select_update_team.setText(teamType);
                                inspectorName = null;
                                inspectorCode = null;
                                select_update_inspector.setText("");
                                handler.sendEmptyMessage(1); //根据单检组检获取检验员
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        })
                        .show();
                break;
            case R.id.select_update_inspector:
                try {
                    String team = select_update_team.getText().toString();
                    if ("单检".equals(team)) {
                        return;
                    }
                    if (null != inspectorBean) {
                        if (null == materialDialog) {
                            List<Integer> list = new ArrayList<Integer>();
                            for (int i = 0; i < inspectorBean.getTeam().size(); i++) {
                                if (inspectorBean.getTeam().get(i).isIsCheck()) {
                                    list.add(i);
                                }
                            }
                            Integer[] strings = new Integer[list.size()];
                            Integer[] selectedIndices = (StringUtils.isEmpty(Guid)) ? list.toArray(strings) : null;
                            LogUtils.e("selectedIndices = " + (null == selectedIndices));
                            materialDialog = new MaterialDialog.Builder(this)
                                    .title("请选择巡检员")
                                    .positiveText("确认")
                                    .items(inspectorBean.getTeam())
                                    .itemsCallbackMultiChoice(selectedIndices, new myCallback())
                                    .show();
                        } else {
                            materialDialog.show();
                        }
                        LogUtils.e("开始for循环");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.select_update_search:
                flowingCode = select_update_flowing.getText().toString();
                if (!StringUtils.isEmpty(flowingCode)) {
                    handler.sendEmptyMessage(2);//通过流转单获取数据
                } else {
                    ToastUtils.showShort("请输入流转单号");
                }
                break;
            case R.id.select_update_scan:
                startActivityForResult(new Intent(this, MyCaptureActivity.class), BaseConstant.result_scan);
                break;
            case R.id.select_update_group:
                if (null != groupBean) {
                    new MaterialDialog.Builder(this)
                            .title("请选择生产组别")
                            .items(groupBean.getData())
                            .itemsCallback((dialog, view1, position, text) -> {
                                try {
                                    groupName = groupBean.getData().get(position).getCDepName();
                                    groupCode = groupBean.getData().get(position).getCDepCode();
                                    select_update_group.setText(groupName);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            })
                            .show();
                }
                break;
            case R.id.select_update_time:
                TimeUtils.showDate(this, new TimeUtils.onListener() {
                    @Override
                    public void onShow(String time) {
                        select_update_time.setText(time);
                    }
                });
                break;
            case R.id.select_update_result:
                new MaterialDialog.Builder(this)
                        .items("合格", "不合格")
                        .itemsCallback((dialog, view1, position, text) -> {
                            result = (position == 0) ? "合格" : "不合格";
                            select_update_result.setText(result);
                        })
                        .show();
                break;
            case R.id.select_update_update:
                try {
                    teamType = select_update_team.getText().toString();
                    reCheck = select_update_reCheck.isChecked() ? 1 : 0;
                    flowingCode = select_update_flowing.getText().toString();
                    cInvName = select_update_name.getText().toString();
                    packNum = select_update_pack.getText().toString();
                    comNum = select_update_com.getText().toString();
                    percent = select_update_percent.getText().toString();
                    checkNum = select_update_check.getText().toString();
                    area = select_update_area.getText().toString();
                    groupName = select_update_group.getText().toString();
                    inspectorName = select_update_inspector.getText().toString();
                    inspectorTime = select_update_time.getText().toString();
                    result = select_update_result.getText().toString();
                    mark = select_update_mark.getText().toString();

                    if (StringUtils.isEmpty(teamType)) {
                        ToastUtils.showShort("请选择单检或组检");
                        return;
                    }
                    if (StringUtils.isEmpty(flowingCode)) {
                        ToastUtils.showShort("请输入流转单号");
                        return;
                    }
                    if (StringUtils.isEmpty(cInvName)) {
                        ToastUtils.showShort("成品名称不能为空");
                        return;
                    }
                    if (StringUtils.isEmpty(packNum)) {
                        ToastUtils.showShort("本包数不能为空");
                        return;
                    }
                    if (StringUtils.isEmpty(comNum)) {
                        ToastUtils.showShort("部件数不能为空");
                        return;
                    }
                    if (StringUtils.isEmpty(percent)) {
                        ToastUtils.showShort("抽检比例不能为空");
                        return;
                    }
                    if (StringUtils.isEmpty(checkNum)) {
                        ToastUtils.showShort("全检数不能为空");
                        return;
                    }
                    if (StringUtils.isEmpty(area)) {
                        ToastUtils.showShort("请输入厂区");
                        return;
                    }
                    if (StringUtils.isEmpty(groupName)) {
                        ToastUtils.showShort("请选择生产组别");
                        return;
                    }
                    if (StringUtils.isEmpty(inspectorName)) {
                        ToastUtils.showShort("请选择巡检员");
                        return;
                    }
                    if (StringUtils.isEmpty(inspectorTime)) {
                        ToastUtils.showShort("请选择检验日期");
                        return;
                    }
                    LogUtils.e("Guid = " + Guid);
                    LogUtils.e("ID = " + ID);
                    LogUtils.e("teamType = " + teamType);
                    LogUtils.e("reCheck = " + reCheck);
                    LogUtils.e("flowingCode = " + flowingCode);
                    LogUtils.e("cInvName = " + cInvName);
                    LogUtils.e("cInvCode = " + cInvCode);
                    LogUtils.e("packNum = " + packNum);
                    LogUtils.e("comNum = " + comNum);
                    LogUtils.e("percent = " + percent);
                    LogUtils.e("checkNum = " + checkNum);
                    LogUtils.e("area = " + area);
                    LogUtils.e("groupName = " + groupName);
                    LogUtils.e("groupCode = " + groupCode);
                    LogUtils.e("inspectorName = " + inspectorName);
                    LogUtils.e("inspectorCode = " + inspectorCode);
                    LogUtils.e("inspectorTime = " + inspectorTime);
                    LogUtils.e("result = " + result);
                    LogUtils.e("mark = " + mark);
                    commitDialog = new MaterialDialog.Builder(this)
                            .content("提交数据中...")
                            .progress(true, 0)
                            .cancelable(false)
                            .show();
                    handler.sendEmptyMessage(5);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.select_update_area:
                if (null != allAreaBean && null != allAreaBean.getData() && allAreaBean.getData().size() > 0) {
                    new MaterialDialog.Builder(this)
                            .items(allAreaBean.getData())
                            .itemsCallback((dialog, view1, position, text) -> {
                                select_update_area.setText(allAreaBean.getData().get(position).getItemName());
                            })
                            .show();
                }
                break;
        }
    }

    public Handler handler = new Handler(message -> {
        String LoginName = ACache.get(this).getAsString("LoginName");
        String UserName = ACache.get(this).getAsString("UserName");
        LogUtils.e("message.what = " + message.what);
        switch (message.what) {
            case 6://获取默认厂区
                presenter2.getDefaultArea(LoginName);
                break;
            case 0://获取所有生产组别
                presenter.getGroups();
                break;
            case 1://根据单检组检获取检验员
                teamType = select_update_team.getText().toString();
                presenter.getInspector(LoginName, teamType);
                break;
            case 2://通过流转单获取数据
                presenter.getSelectFlowing(flowingCode, inspectorCode, LoginName);
                break;
            case 3://获取厂区列表
                presenter2.getAllArea();
                break;
            case 5://保存缝制抽检
                presenter.save(LoginName,
                        UserName,
                        Guid,
                        ID,
                        teamType,
                        reCheck,
                        flowingCode,
                        cInvName,
                        cInvCode,
                        packNum,
                        comNum,
                        percent,
                        checkNum,
                        area,
                        groupName,
                        groupCode,
                        inspectorName,
                        inspectorCode,
                        inspectorTime,
                        result,
                        mark);
                break;
        }
        return false;
    });

    private InspectorBean inspectorBean;

    @Override
    public void onSuccess(InspectorBean inspectorBean) {
        this.inspectorBean = inspectorBean;
        String inspector = select_update_inspector.getText().toString();
        if (StringUtils.isEmpty(inspector) && inspectorBean.getTeam().size() > 0) {
            LogUtils.e("检验员为空，根据接口选择");
            StringBuilder sb_name = new StringBuilder();
            StringBuilder sb_code = new StringBuilder();
            for (int i = 0; i < inspectorBean.getTeam().size(); i++) {
                if (inspectorBean.getTeam().get(i).isIsCheck()) {
                    if (!StringUtils.isEmpty(sb_name)) {
                        sb_name.append(",");
                        sb_code.append(",");
                    }
                    sb_name.append(inspectorBean.getTeam().get(i).getTeamName());
                    sb_code.append(inspectorBean.getTeam().get(i).getTeamCode());
                }
            }
            LogUtils.e("sb_name = " + sb_name);
            LogUtils.e("sb_code = " + sb_code);
            inspectorName = sb_name.toString();
            inspectorCode = sb_code.toString();
            select_update_inspector.setText(inspectorName);
        } else {
            LogUtils.e("已经有检验员，不赋值");
        }
    }

    @Override
    public void onSuccess(SelectFlowingBean selectFlowingBean) {
        cInvName = selectFlowingBean.getCInvName();
        cInvCode = selectFlowingBean.getCInvCode();
        packNum = selectFlowingBean.getPackQty();
        comNum = selectFlowingBean.getComNum();
        percent = selectFlowingBean.getCheck_FZ();
        /**
         * 需要改成本包数*抽检比例  12*0.1=1.2   小数位进位得到2   抽检数=2*部件数6=12
         */
        try {
            double double_packNum = Double.parseDouble(packNum);//本包数
            double double_comNum = Double.parseDouble(comNum);//部件数
            double double_percent = Double.parseDouble(percent);//部件数

            int double_check = (int) ((Math.ceil(double_packNum * double_percent / 100)) * double_comNum);

            //;int double_check = (int) Math.ceil(double_packNum * double_comNum * double_percent/100);
            LogUtils.e("double_check = " + double_check);
            checkNum = String.valueOf(double_check);
            LogUtils.e("checkNum = " + checkNum);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            checkNum = "0.0";
        }
        area = selectFlowingBean.getFacArea();
        groupName = selectFlowingBean.getGroupName();
        groupCode = selectFlowingBean.getGroupCode();

        select_update_name.setText(cInvName);
        select_update_pack.setText(packNum);
        select_update_com.setText(comNum);
        select_update_percent.setText(percent);
        select_update_check.setText(checkNum);
        select_update_area.setText(area);
        select_update_group.setText(groupName);

        //部件数,抽检比例 输入监控
        select_update_com.addTextChangedListener(new myTextWatcher());
        select_update_percent.addTextChangedListener(new myTextWatcher());
    }

    private GroupBean groupBean;

    @Override
    public void onSuccess(GroupBean groupBean) {
        this.groupBean = groupBean;
    }

    @Override
    public void onSuccess(BaseBean baseBean) {
        ToastUtils.showShort(baseBean.getMessage());
        setResult(BaseConstant.result_code);
        finish();
    }

    @Override
    public void onSuccess(HangUpdateLoginBean hangUpdateLoginBean) {
        try {
            area = hangUpdateLoginBean.getData().get(0).getStaffArea();
            select_update_area.setText(area);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private AllAreaBean allAreaBean;

    @Override
    public void onSuccess(AllAreaBean allAreaBean) {
        this.allAreaBean = allAreaBean;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == BaseConstant.result_scan && null != data && null != data.getExtras()) {
            //处理扫描结果（在界面上显示）
            String result = FlowingUtils.getFlowing(data.getStringExtra(Intents.Scan.RESULT));
            if (StringUtils.isEmpty(result)) {
                ToastUtils.showShort("请填写流转单号");
            } else {
                flowingCode = result;
                select_update_flowing.setText(flowingCode);
                handler.sendEmptyMessage(2); //根据流转单获取数据
            }
        }
    }

    private class myCallback implements MaterialDialog.ListCallbackMultiChoice {

        @Override
        public boolean onSelection(MaterialDialog dialog, Integer[] position, CharSequence[] text) {
            try {
                StringBuilder sb_code = new StringBuilder();
                StringBuilder sb_name = new StringBuilder();
                for (int p : position) {
                    String code = inspectorBean.getTeam().get(p).getTeamCode();
                    String name = inspectorBean.getTeam().get(p).getTeamName();
                    if (sb_code.length() != 0) {
                        sb_code.append(",");
                        sb_name.append(",");
                    }
                    sb_code.append(code);
                    sb_name.append(name);
                    inspectorCode = sb_code.toString();
                    inspectorName = sb_name.toString();
                    select_update_inspector.setText(inspectorName);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }
    }

    //部件数输入监控
    //抽检比例输入监控
    private class myTextWatcher extends BaseTextWatcher {

        @Override
        public void onTextChanged(String message) {
            try {
                String packNum = select_update_pack.getText().toString();
                String comNum = select_update_com.getText().toString();
                String percent = select_update_percent.getText().toString();
                if (!StringUtils.isEmpty(packNum) && !StringUtils.isEmpty(comNum) && !StringUtils.isEmpty(percent)) {
                    double double_packNum = Double.parseDouble(packNum);
                    double double_comNum = Double.parseDouble(comNum);
                    double double_percent = Double.parseDouble(percent);
                    int double_check = (int) ((Math.ceil(double_packNum * double_percent / 100)) * double_comNum);
                    //int double_check = (int) Math.ceil(double_packNum * double_comNum * double_percent / 100);
                    checkNum = String.valueOf(double_check);
                    select_update_check.setText(checkNum);
                    LogUtils.e("计算数值 checkNum = " + checkNum);
                } else {
                    select_update_check.setText("");
                    LogUtils.e("本包数或部件数或抽检比例为空，不计算数值");
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
                LogUtils.e("输入有误");
            }
        }
    }
}